const log4js = require('log4js');
const methods = ["trace", "debug", "info", "warn", "error", "fatal", "mark"];
const access = require('./access')
module.exports = (opts) => {
  let ctxLogger = {};
  const defaultInfo = {
    env: 'dev',
    dir: 'logs',
    appLogLevel: 'info'
  }

  const options = Object.assign({}, defaultInfo, opts || {});
  const { env, dir, appLogLevel } = options;
  const appenders = {
    cheese: {
      type: 'dateFile', // 日志类型 
      filename: `${dir}/task`, // 输出的文件名
      pattern: '-yyyy-MM-dd.log', // 文件名增加后缀
      alwaysIncludePattern: true // 是否总是有后缀名
    }
  }

  if (env === 'dev' || env === 'local' || env === 'development') {
    appenders.out = {
      type: 'console'
    }
  }

  const config = {
    appenders,
    categories: {
      default: {
        appenders:Object.keys(appenders),
        level: appLogLevel
      }
    }
  }



  return async(ctx, next) => {

    const start = +new Date();
    log4js.configure(config);

    const logger = log4js.getLogger('cheese');

    methods.forEach((method, i) => {
      ctxLogger[method] = (message) => {
        logger[method](access(ctx, message, {}))
      }
    })
    ctx.log = ctxLogger
    await next()
    const end = +new Date()
    const responseTime = end - start;
    logger.info(access(ctx,`响应时间为:${responseTime/1000}s`, {}))
  }
}